from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from markdown import Markdown
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField

class Category(models.Model):
    """文章分类"""
    title = models.CharField(max_length=100)
    created = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['-created']
        verbose_name = u"分类"
        verbose_name_plural = u"分类"

    def __str__(self):
        return self.title


class Tag(models.Model):
    """文章标签"""
    text = models.CharField(max_length=30)

    class Meta:
        ordering = ['-id']
        verbose_name = u"标签"
        verbose_name_plural = u"标签"

    def __str__(self):
        return self.text


class Avatar(models.Model):
    content = models.ImageField(upload_to='avatar/%Y%m%d')


# 博客文章 model
class Article(models.Model):
    # 标题图
    avatar = models.ForeignKey(
        Avatar,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='article'
    )
    
    # 标签
    tags = models.ManyToManyField(
        Tag,
        blank=True,
        related_name='articles'
    )

    # 分类
    category = models.ForeignKey(
        Category,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='articles'
    )

    author = models.ForeignKey(
        User, 
        null=True,
        on_delete=models.CASCADE, 
        related_name='articles'
    )
    # 标题
    title = models.CharField(max_length=100,verbose_name='标题')
    # 正文
    body = RichTextUploadingField(verbose_name='正文')
    # 创建时间
    created = models.DateTimeField(default=timezone.now,verbose_name='创建时间')
    # 更新时间
    updated = models.DateTimeField(auto_now=True)
    total_views = models.PositiveIntegerField(default=0,verbose_name='点赞数')    

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created']
        verbose_name = u"文章列表"
        verbose_name_plural = u"文章列表"

    def get_md(self):
        md = Markdown(
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
            ]
        )
        md_body = md.convert(self.body)
        # toc 是渲染后的目录
        return md_body, md.toc


